package com.gj.demojuc.chap06;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Runnable接口的run方法没有返回结果不能声明异常
 * 来自于java.lang包
 */
class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "come in");
    }
}

/**
 * Callable接口的call方法有返回结果，可以声明异常
 * java.util.current包 对run进行增强
 */
class MyCallable implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "call come in");
        return 100;
    }
}
//Callable接口创建线程
public class CallableDemo {
    public static void main(String[] args) {
//        MyRunnable myRunnable = new MyRunnable();
//        Thread t1 = new Thread(myRunnable,"T1");
//        t1.start();
//        Thread t2 = new Thread(myRunnable,"T2");
//        t2.start();
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        //不能直接接受callable实现类，但是可以接受futuretask类型，因为futuretask实现了runnable。
        Thread t3 = new Thread(futureTask,"T3");
        t3.start();
        
        try {
            Integer result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
